const axios = require('axios');

/**
 * 获取所有当前可买比赛数据
 * @returns {Promise<Object>} 返回所有比赛数据
 */
async function getAllMatches() {
  try {
    // API URL和参数
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/football/getMatchCalculatorV1.qry';
    const API_PARAMS = {
      poolCode: 'hhad,had', // 获取胜平负和让球胜平负
      channel: 'c'
    };

    // console.log('正在获取全部比赛数据...');
    const response = await axios.get(API_URL, { params: API_PARAMS });

    // 验证请求是否成功
    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    const matchInfoList = response.data.value.matchInfoList || [];
    let totalMatches = 0;

    // 计算总比赛数量
    matchInfoList.forEach(dateInfo => {
      totalMatches += (dateInfo.subMatchList || []).length;
    });

    // console.log(`成功获取比赛数据，共 ${matchInfoList.length} 天, ${totalMatches} 场比赛`);

    return response.data;
  } catch (error) {
    console.error('获取全部比赛数据出错:', error.message);
    throw error;
  }
}

/**
 * 获取全部比赛并提取关键信息
 * @returns {Promise<Array>} 返回处理后的比赛数组
 */
async function getFormattedMatches() {
  try {
    const allData = await getAllMatches();
    const formattedMatches = [];

    // 遍历每一天的比赛
    allData.value.matchInfoList.forEach(dateInfo => {
      const businessDate = dateInfo.businessDate;
      const weekday = dateInfo.weekday;

      // 遍历该天的所有比赛
      (dateInfo.subMatchList || []).forEach(match => {
        formattedMatches.push({
          matchId: match.matchId,
          matchNum: match.matchNumStr,
          matchTime: `${businessDate} ${match.matchTime}`,
          weekday: weekday,
          leagueId: match.leagueId,
          leagueName: match.leagueAbbName,
          homeTeam: {
            id: match.homeTeamId,
            name: match.homeTeamAbbName,
            fullName: match.homeTeamAllName,
            rank: match.homeRank
          },
          awayTeam: {
            id: match.awayTeamId,
            name: match.awayTeamAbbName,
            fullName: match.awayTeamAllName,
            rank: match.awayRank
          },
          odds: {
            had: match.had || {}, // 胜平负赔率
            hhad: match.hhad || {} // 让球胜平负赔率
          }
        });
      });
    });

    return formattedMatches;
  } catch (error) {
    console.error('获取格式化比赛数据出错:', error.message);
    throw error;
  }
}

/**
 * 获取所有球队信息
 * @returns {Promise<Array>} 返回所有球队信息的数组
 */
async function getAllTeams() {
  try {
    const allData = await getAllMatches();
    const teamsMap = new Map(); // 使用Map避免重复

    // 遍历每一天的比赛
    allData.value.matchInfoList.forEach(dateInfo => {
      // 遍历该天的所有比赛
      (dateInfo.subMatchList || []).forEach(match => {
        // 提取主队信息
        if (match.homeTeamId) {
          teamsMap.set(match.homeTeamId, {
            id: match.homeTeamId,
            name: match.homeTeamAbbName,
            fullName: match.homeTeamAllName,
            code: match.homeTeamCode,
            rank: match.homeRank || '',
            leagueId: match.leagueId,
            leagueName: match.leagueAbbName
          });
        }

        // 提取客队信息
        if (match.awayTeamId) {
          teamsMap.set(match.awayTeamId, {
            id: match.awayTeamId,
            name: match.awayTeamAbbName,
            fullName: match.awayTeamAllName,
            code: match.awayTeamCode,
            rank: match.awayRank || '',
            leagueId: match.leagueId,
            leagueName: match.leagueAbbName
          });
        }
      });
    });

    // 将Map转为数组
    return Array.from(teamsMap.values());
  } catch (error) {
    console.error('获取所有球队数据出错:', error.message);
    throw error;
  }
}

/**
 * 从比赛数据中提取所有球队信息
 * @param {Object} allMatchesData - 所有比赛数据
 * @returns {Array<Object>} 返回球队列表，包含ID、名称等信息
 */
function extractTeamInfo(allMatchesData) {
  const teamsMap = new Map(); // 使用Map避免重复

  if (!allMatchesData.value || !allMatchesData.value.matchInfoList) {
    throw new Error('无效的比赛数据格式');
  }

  // 遍历每一天的比赛
  allMatchesData.value.matchInfoList.forEach(dateInfo => {
    // 遍历该天的所有比赛
    (dateInfo.subMatchList || []).forEach(match => {
      // 提取主队信息
      if (match.homeTeamId) {
        teamsMap.set(match.homeTeamId, {
          id: match.homeTeamId,
          name: match.homeTeamAbbName,
          fullName: match.homeTeamAllName,
          code: match.homeTeamCode,
          rank: match.homeRank || ''
        });
      }

      // 提取客队信息
      if (match.awayTeamId) {
        teamsMap.set(match.awayTeamId, {
          id: match.awayTeamId,
          name: match.awayTeamAbbName,
          fullName: match.awayTeamAllName,
          code: match.awayTeamCode,
          rank: match.awayRank || ''
        });
      }
    });
  });

  // 将Map转为数组
  return Array.from(teamsMap.values());
}

/**
 * 获取球队历史比赛数据
 * @param {number} teamId - 球队ID
 * @param {Object} options - 可选参数
 * @param {string} options.homeAwayFlag - 筛选主场/客场比赛，值可以是'home'或'away'，不传则获取全部
 * @param {number} options.termLimits - 获取的比赛数量，默认20场
 * @param {string[]} options.leagueIds - 联赛ID列表，默认包含多个联赛
 * @returns {Promise<Object>} 返回比赛数据
 */
async function getTeamHistoryMatches(params) {
  try {
    // 发送API请求
    const url = 'https://webapi.sporttery.cn/gateway/uniform/football/team/getMatchResultV1.qry';
    const response = await axios.get(url, { params });

    // 验证响应数据
    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    return response.data?.value?.matchList || [];
  } catch (error) {
    console.error('获取球队历史比赛数据出错:', error.message);
    throw error;
  }
}

/**
 * 分析球队历史比赛数据
 * @param {Object} teamHistoryData - 球队历史比赛数据
 * @param {number} teamId - 球队ID
 * @returns {Object} 返回分析结果
 */
function analyzeTeamHistory(teamHistoryData, teamId) {
  try {
    if (!teamHistoryData || !teamHistoryData.value) {
      return { error: '无效的比赛数据' };
    }

    // 获取球队信息
    const teamInfo = teamHistoryData.value.team || {};

    // 获取比赛列表
    const matches = teamHistoryData.value.matchResults || [];
    if (!matches.length) {
      return {
        team: teamInfo,
        error: '没有找到比赛数据'
      };
    }

    // 基础统计
    const stats = {
      totalMatches: matches.length,
      wins: 0,
      draws: 0,
      losses: 0,
      goalsScored: 0,
      goalsConceded: 0,
      cleanSheets: 0,
      homeMatches: 0,
      homeWins: 0,
      awayMatches: 0,
      awayWins: 0,
      recentForm: []
    };

    // 分析每场比赛
    matches.forEach(match => {
      // 提取比赛信息
      const homeTeamId = match.homeTeam?.id;
      const awayTeamId = match.awayTeam?.id;
      const isHome = homeTeamId === teamId;
      const homeGoals = parseInt(match.homeScore || 0);
      const awayGoals = parseInt(match.awayScore || 0);

      // 统计进球和失球
      const teamGoals = isHome ? homeGoals : awayGoals;
      const opponentGoals = isHome ? awayGoals : homeGoals;
      stats.goalsScored += teamGoals;
      stats.goalsConceded += opponentGoals;

      // 统计胜平负
      if (homeGoals === awayGoals) {
        stats.draws++;
        stats.recentForm.push('D');
      } else if ((isHome && homeGoals > awayGoals) || (!isHome && awayGoals > homeGoals)) {
        stats.wins++;
        stats.recentForm.push('W');
        if (isHome) stats.homeWins++;
        else stats.awayWins++;
      } else {
        stats.losses++;
        stats.recentForm.push('L');
      }

      // 统计主客场
      if (isHome) {
        stats.homeMatches++;
        if (awayGoals === 0) stats.cleanSheets++;
      } else {
        stats.awayMatches++;
        if (homeGoals === 0) stats.cleanSheets++;
      }
    });

    // 计算胜率和其他衍生指标
    stats.winRate = (stats.wins / stats.totalMatches * 100).toFixed(2) + '%';
    stats.homeWinRate = stats.homeMatches > 0 ? (stats.homeWins / stats.homeMatches * 100).toFixed(2) + '%' : '0%';
    stats.awayWinRate = stats.awayMatches > 0 ? (stats.awayWins / stats.awayMatches * 100).toFixed(2) + '%' : '0%';
    stats.goalsPerMatch = (stats.goalsScored / stats.totalMatches).toFixed(2);
    stats.concededPerMatch = (stats.goalsConceded / stats.totalMatches).toFixed(2);
    stats.recentFormString = stats.recentForm.slice(0, 5).join('-');

    return {
      team: teamInfo,
      stats,
      matches
    };
  } catch (error) {
    console.error('分析球队历史比赛数据出错:', error.message);
    return { error: error.message };
  }
}

// 获取指定比赛的让球值和赔率
function getMatchOddsInfo(match) {
  const had = match.odds?.had || {};
  const hhad = match.odds?.hhad || {};

  return {
    // 基本信息
    matchId: match.matchId,
    matchNum: match.matchNum,
    homeTeam: match.homeTeam?.name || '未知',
    awayTeam: match.awayTeam?.name || '未知',

    // 让球信息
    handicap: hhad.goalLine || '0',

    // 胜平负赔率
    normalOdds: {
      win: had.h || '-',
      draw: had.d || '-',
      lose: had.a || '-'
    },

    // 让球胜平负赔率
    handicapOdds: {
      win: hhad.h || '-',
      draw: hhad.d || '-',
      lose: hhad.a || '-'
    }
  };
}

// 使用示例
async function showOddsExample() {
  const matches = await getFormattedMatches();

  matches.forEach(match => {
    const info = getMatchOddsInfo(match);
    console.log(`${info.matchNum} ${info.homeTeam} vs ${info.awayTeam}`);
    console.log(`让球: ${info.handicap}`);
    console.log(`胜平负: ${info.normalOdds.win}/${info.normalOdds.draw}/${info.normalOdds.lose}`);
    console.log(`让球胜平负: ${info.handicapOdds.win}/${info.handicapOdds.draw}/${info.handicapOdds.lose}`);
    console.log('-'.repeat(40));
  });
}

/**
 * 获取比赛的积分榜数据
 * @param {string} gmMatchId - 比赛ID
 * @returns {Promise<Object>} 返回积分榜数据
 */
async function getMatchTables(gmMatchId) {
  try {
    const url = 'https://webapi.sporttery.cn/gateway/uniform/football/getMatchTablesV2.qry';
    const response = await axios.get(url, {
      params: { gmMatchId }
    });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    return response.data.value;
  } catch (error) {
    console.error('获取积分榜数据出错:', error.message);
    throw error;
  }
}

/**
 * 格式化积分榜数据，提取关键信息
 * @param {Object} tablesData - 积分榜原始数据
 * @returns {Object} 格式化后的积分榜数据
 */
function formatTablesData(tablesData) {
  if (!tablesData) return null;

  const formatTeamData = (teamData) => {
    if (!teamData) return null;

    return {
      总积分榜: {
        球队: teamData.total?.teamShortName || '',
        排名: teamData.total?.ranking || '',
        积分: teamData.total?.points || '',
        场次: teamData.total?.totalLegCnt || 0,
        胜: teamData.total?.winGoalMatchCnt || 0,
        平: teamData.total?.drawMatchCnt || 0,
        负: (teamData.total?.totalLegCnt || 0) - (teamData.total?.winGoalMatchCnt || 0) - (teamData.total?.drawMatchCnt || 0),
        进球: teamData.total?.goalCnt || 0,
        失球: teamData.total?.lossGoalCnt || 0,
        净胜球: teamData.total?.netGoal || 0,
        胜率: teamData.total?.winProbability || '0%'
      },
      主场积分榜: {
        球队: teamData.home?.teamShortName || '',
        排名: teamData.home?.ranking || '',
        积分: teamData.home?.points || '',
        场次: teamData.home?.totalLegCnt || 0,
        胜: teamData.home?.winGoalMatchCnt || 0,
        平: teamData.home?.drawMatchCnt || 0,
        负: (teamData.home?.totalLegCnt || 0) - (teamData.home?.winGoalMatchCnt || 0) - (teamData.home?.drawMatchCnt || 0),
        进球: teamData.home?.goalCnt || 0,
        失球: teamData.home?.lossGoalCnt || 0,
        净胜球: teamData.home?.netGoal || 0,
        胜率: teamData.home?.winProbability || '0%'
      },
      客场积分榜: {
        球队: teamData.away?.teamShortName || '',
        排名: teamData.away?.ranking || '',
        积分: teamData.away?.points || '',
        场次: teamData.away?.totalLegCnt || 0,
        胜: teamData.away?.winGoalMatchCnt || 0,
        平: teamData.away?.drawMatchCnt || 0,
        负: (teamData.away?.totalLegCnt || 0) - (teamData.away?.winGoalMatchCnt || 0) - (teamData.away?.drawMatchCnt || 0),
        进球: teamData.away?.goalCnt || 0,
        失球: teamData.away?.lossGoalCnt || 0,
        净胜球: teamData.away?.netGoal || 0,
        胜率: teamData.away?.winProbability || '0%'
      }
    };
  };

  return {
    联赛信息: {
      联赛: tablesData.leagueShortName || '',
      赛季: tablesData.seasonName || '',
      阶段: tablesData.homeTables?.total?.phaseName || ''
    },
    主队数据: formatTeamData(tablesData.homeTables),
    客队数据: formatTeamData(tablesData.awayTables)
  };
}

/**
 * 打印积分榜数据（表格形式）
 * @param {Object} formattedData - 格式化后的积分榜数据
 */
function printTablesData(formattedData) {
  if (!formattedData) {
    console.log('没有积分榜数据');
    return;
  }

  console.log(`\n========== ${formattedData.联赛信息.联赛} ${formattedData.联赛信息.赛季} ${formattedData.联赛信息.阶段} ==========\n`);

  // 打印主队数据
  console.log(`🏠 主队: ${formattedData.主队数据.总积分榜.球队}`);
  console.log('┌─────────────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬────────┐');
  console.log('│    类型     │ 排名 │ 积分 │ 场次 │  胜  │  平  │  负  │ 进球 │ 失球 │净胜球│  胜率  │');
  console.log('├─────────────┼──────┼──────┼──────┼──────┼──────┼──────┼──────┼──────┼──────┼────────┤');

  ['总积分榜', '主场积分榜', '客场积分榜'].forEach(type => {
    const data = formattedData.主队数据[type];
    console.log(`│ ${type.padEnd(11)} │ ${String(data.排名).padStart(4)} │ ${String(data.积分).padStart(4)} │ ${String(data.场次).padStart(4)} │ ${String(data.胜).padStart(4)} │ ${String(data.平).padStart(4)} │ ${String(data.负).padStart(4)} │ ${String(data.进球).padStart(4)} │ ${String(data.失球).padStart(4)} │ ${String(data.净胜球).padStart(4)} │ ${data.胜率.padStart(6)} │`);
  });
  console.log('└─────────────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴────────┘\n');

  // 打印客队数据
  console.log(`✈️  客队: ${formattedData.客队数据.总积分榜.球队}`);
  console.log('┌─────────────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬────────┐');
  console.log('│    类型     │ 排名 │ 积分 │ 场次 │  胜  │  平  │  负  │ 进球 │ 失球 │净胜球│  胜率  │');
  console.log('├─────────────┼──────┼──────┼──────┼──────┼──────┼──────┼──────┼──────┼──────┼────────┤');

  ['总积分榜', '主场积分榜', '客场积分榜'].forEach(type => {
    const data = formattedData.客队数据[type];
    console.log(`│ ${type.padEnd(11)} │ ${String(data.排名).padStart(4)} │ ${String(data.积分).padStart(4)} │ ${String(data.场次).padStart(4)} │ ${String(data.胜).padStart(4)} │ ${String(data.平).padStart(4)} │ ${String(data.负).padStart(4)} │ ${String(data.进球).padStart(4)} │ ${String(data.失球).padStart(4)} │ ${String(data.净胜球).padStart(4)} │ ${data.胜率.padStart(6)} │`);
  });
  console.log('└─────────────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴────────┘');
}

// 示例使用
async function example() {
  try {
    // // 测试积分榜数据获取
    // console.log('正在获取积分榜数据...');
    // const tablesData = await getMatchTables('2033597');
    // const formattedTables = formatTablesData(tablesData);

    // // 打印格式化的积分榜数据
    // printTablesData(formattedTables);

    // // 也可以打印原始数据查看
    // console.log('\n原始数据结构:');
    // console.log(JSON.stringify(tablesData, null, 2));

    // 获取完整赔率变化数据
    // const oddsData = await getOddsHistory('2033598');

    // // 获取特定类型赔率数据
    // // https://www.sporttery.cn/jc/zqdz/index.html?showType=3&mid=2033598
    // const hadData = await getOddsByType('2033598', 'HAD'); // 胜平负
    // const hhadData = await getOddsByType('2033598', 'HHAD'); // 让球胜平负  
    // const crsData = await getOddsByType('2033598', 'CRS'); // 比分
    // const ttgData = await getOddsByType('2033598', 'TTG'); // 总进球数
    // const hafuData = await getOddsByType('2033598', 'HAFU'); // 半全场

    // console.log("crsData", crsData);

    // 获取开奖结果
    const results = await getMatchResults('2033598');
    // console.log('开奖结果:', results);

    // 格式化打印开奖结果
    printMatchResults(results);


    return;
  } catch (error) {
    console.error('示例运行出错:', error.message);
  }
}

/**
 * 下注方式类型定义
 */
const BET_TYPES = {
  HAD: {
    key: 'hadList',
    name: '胜平负固定奖金',
    description: '主队胜(H)、平局(D)、客队胜(A)',
    fields: ['h', 'd', 'a']
  },
  HHAD: {
    key: 'hhadList',
    name: '让球胜平负固定奖金',
    description: '让球胜平负，包含让球数',
    fields: ['h', 'd', 'a', 'goalLine']
  },
  CRS: {
    key: 'crsList',
    name: '比分固定奖金',
    description: '准确比分投注',
    fields: ['s00s00', 's00s01', 's00s02', 's01s00', 's01s01', 's02s00', 's02s01', 's03s00', 's04s00', 's05s00', 's-1sd', 's-1sh', 's-1sa']
  },
  TTG: {
    key: 'ttgList',
    name: '总进球数固定奖金',
    description: '全场总进球数0-7+球',
    fields: ['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7']
  },
  HAFU: {
    key: 'hafuList',
    name: '半全场胜平负固定奖金',
    description: '半场/全场结果组合',
    fields: ['hh', 'hd', 'ha', 'dh', 'dd', 'da', 'ah', 'ad', 'aa']
  }
};

/**
 * 获取赔率变化情况
 * @param {string} matchId - 比赛ID
 * @returns {Promise<Object>} 返回赔率变化数据
 */
async function getOddsHistory(matchId) {
  try {
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/football/getFixedBonusV1.qry';
    const API_PARAMS = {
      clientCode: '3001',
      matchId: matchId
    };

    console.log(`正在获取比赛 ${matchId} 的赔率变化数据...`);
    const response = await axios.get(API_URL, { params: API_PARAMS });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    const oddsHistory = response.data.value.oddsHistory;
    const matchResults = response.data.value.matchResultList;

    // 格式化赔率历史数据
    const formattedOdds = {};

    // 遍历每种下注类型
    Object.entries(BET_TYPES).forEach(([typeKey, typeInfo]) => {
      const historyData = oddsHistory[typeInfo.key];
      if (historyData && historyData.length > 0) {
        formattedOdds[typeKey] = {
          type: typeInfo.name,
          description: typeInfo.description,
          history: historyData.map(record => {
            const formattedRecord = {
              updateDate: record.updateDate,
              updateTime: record.updateTime,
              odds: {},
              changes: {} // 记录变化标志
            };

            // 提取对应字段的赔率和变化标志
            typeInfo.fields.forEach(field => {
              if (record[field] !== undefined) {
                formattedRecord.odds[field] = record[field];
                // 获取变化标志（字段名+f）
                const changeFlag = record[field + 'f'];
                if (changeFlag !== undefined) {
                  formattedRecord.changes[field] = changeFlag;
                }
              }
            });

            // 特殊处理让球数
            if (record.goalLine !== undefined) {
              formattedRecord.goalLine = record.goalLine;
            }

            return formattedRecord;
          })
        };
      }
    });

    // 获取当前最新赔率
    const currentOdds = {};
    matchResults.forEach(result => {
      const betType = Object.keys(BET_TYPES).find(key => key === result.code);
      if (betType) {
        if (!currentOdds[betType]) {
          currentOdds[betType] = {};
        }
        currentOdds[betType][result.combination] = {
          odds: result.odds,
          description: result.combinationDesc,
          goalLine: result.goalLine
        };
      }
    });

    const result = {
      matchInfo: {
        matchId: oddsHistory.matchId,
        homeTeam: {
          id: oddsHistory.homeTeamId,
          name: oddsHistory.homeTeamAllName,
          abbName: oddsHistory.homeTeamAbbName
        },
        awayTeam: {
          id: oddsHistory.awayTeamId,
          name: oddsHistory.awayTeamAllName,
          abbName: oddsHistory.awayTeamAbbName
        },
        league: {
          id: oddsHistory.leagueId,
          name: oddsHistory.leagueAllName,
          abbName: oddsHistory.leagueAbbName
        }
      },
      oddsHistory: formattedOdds,
      currentOdds: currentOdds,
      betTypes: BET_TYPES,
      finalScore: response.data.value.sectionsNo999
    };

    console.log(`成功获取比赛 ${matchId} 的赔率变化数据`);
    return result;

  } catch (error) {
    console.error(`获取比赛 ${matchId} 赔率变化数据出错:`, error.message);
    throw error;
  }
}

/**
 * 根据下注类型获取特定赔率历史
 * @param {string} matchId - 比赛ID
 * @param {string} betType - 下注类型 (HAD, HHAD, CRS, TTG, HAFU)
 * @returns {Promise<Object>} 返回特定类型的赔率变化数据
 */
async function getOddsByType(matchId, betType) {
  try {
    const allOdds = await getOddsHistory(matchId);

    if (!BET_TYPES[betType]) {
      throw new Error(`不支持的下注类型: ${betType}`);
    }

    const typeData = allOdds.oddsHistory[betType];
    if (!typeData) {
      throw new Error(`比赛 ${matchId} 没有 ${BET_TYPES[betType].name} 数据`);
    }

    return {
      matchInfo: allOdds.matchInfo,
      betType: BET_TYPES[betType],
      data: typeData,
      currentOdds: allOdds.currentOdds[betType]
    };

  } catch (error) {
    console.error(`获取比赛 ${matchId} ${betType} 类型赔率数据出错:`, error.message);
    throw error;
  }
}

/**
 * 获取比赛开奖结果
 * @param {string} matchId - 比赛ID
 * @returns {Promise<Object>} 返回开奖结果数据
 */
async function getMatchResults(matchId) {
  try {
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/football/getFixedBonusV1.qry';
    const API_PARAMS = {
      clientCode: '3001',
      matchId: matchId
    };

    console.log(`正在获取比赛 ${matchId} 的开奖结果...`);
    const response = await axios.get(API_URL, { params: API_PARAMS });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    const oddsHistory = response.data.value.oddsHistory;
    const matchResults = response.data.value.matchResultList;
    const finalScore = response.data.value.sectionsNo999;

    // 解析最终比分
    const [homeScore, awayScore] = finalScore ? finalScore.split(':').map(Number) : [null, null];

    const results = {
      matchInfo: {
        matchId: oddsHistory.matchId,
        homeTeam: {
          id: oddsHistory.homeTeamId,
          name: oddsHistory.homeTeamAllName,
          abbName: oddsHistory.homeTeamAbbName
        },
        awayTeam: {
          id: oddsHistory.awayTeamId,
          name: oddsHistory.awayTeamAllName,
          abbName: oddsHistory.awayTeamAbbName
        },
        league: {
          id: oddsHistory.leagueId,
          name: oddsHistory.leagueAllName,
          abbName: oddsHistory.leagueAbbName
        }
      },
      finalScore: {
        home: homeScore,
        away: awayScore,
        display: finalScore
      },
      winningResults: []
    };

    // 从 matchResultList 中提取所有开奖结果
    matchResults.forEach(result => {
      const betTypeInfo = BET_TYPES[result.code];
      const winningResult = {
        code: result.code,
        typeName: betTypeInfo ? betTypeInfo.name : result.code,
        combination: result.combination,
        combinationDesc: result.combinationDesc,
        odds: result.odds,
        goalLine: result.goalLine,
        poolId: result.poolId
      };
      results.winningResults.push(winningResult);
    });

    return results;

  } catch (error) {
    console.error(`获取比赛 ${matchId} 开奖结果出错:`, error.message);
    throw error;
  }
}

/**
 * 格式化开奖结果显示
 * @param {Object} results - 开奖结果数据
 */
function printMatchResults(results) {
  console.log('\n=== 开奖结果 ===');
  console.log(`比赛: ${results.matchInfo.homeTeam.name} vs ${results.matchInfo.awayTeam.name}`);
  console.log(`联赛: ${results.matchInfo.league.name}`);
  console.log(`最终比分: ${results.finalScore.display || '未开奖'}`);

  if (results.winningResults.length > 0) {
    console.log('\n各玩法开奖结果:');
    console.log('┌──────────────────────┬────────────┬──────────┐');
    console.log('│ 玩法类型             │ 开奖结果   │ 中奖赔率 │');
    console.log('├──────────────────────┼────────────┼──────────┤');

    results.winningResults.forEach(result => {
      const typeName = result.typeName.padEnd(20);
      let resultDesc = result.combinationDesc;
      if (result.goalLine) {
        resultDesc = `${result.goalLine}${result.combinationDesc}`;
      }
      const resultDescPadded = resultDesc.padEnd(10);
      const odds = result.odds.padEnd(8);

      console.log(`│ ${typeName} │ ${resultDescPadded} │ ${odds} │`);
    });

    console.log('└──────────────────────┴────────────┴──────────┘');

    // 显示详细信息
    console.log('\n详细开奖信息:');
    results.winningResults.forEach(result => {
      console.log(`${result.typeName}: ${result.combinationDesc} (赔率: ${result.odds})`);
    });

  } else {
    console.log('\n比赛尚未结束，暂无开奖结果');
  }
}

// 导出函数，供其他模块使用
module.exports = {
  getAllMatches,
  extractTeamInfo,
  getTeamHistoryMatches,
  analyzeTeamHistory,
  getFormattedMatches,
  getAllTeams,
  getMatchTables,
  formatTablesData,
  printTablesData,
  getOddsHistory,
  getOddsByType,
  getMatchResults,
  printMatchResults,
  BET_TYPES
};

// 如果直接运行此文件，则执行示例
if (require.main === module) {
  example();
}
